package com.monika.main.system.factory;

import com.monika.main.system.util.ThreadUtil;

import java.util.TimerTask;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Author whh
 * Date 2023/10/11/ 19:59
 * <p></p>
 */
public class AsyncManager {


    private ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10,new DefaultThreadFactory());

    private static final AsyncManager me = new AsyncManager();


    private AsyncManager(){}

    public static AsyncManager me(){
        return me;
    }


    /**
     * 提交任务
     * @param task
     */
    public void submit(Runnable task,long delay){
        if(delay == 0){
            delay = OPERATE_DELAY_TIME;
        }
        this.executor.schedule(task,delay, TimeUnit.SECONDS);
    }





    /**
     * 线程池工厂
     */
    private static class DefaultThreadFactory implements ThreadFactory{
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

    /**
     * 操作延迟4毫秒
     */
    private static final int OPERATE_DELAY_TIME = 4;
    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task)
    {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown()
    {
        ThreadUtil.shutdownAndAwaitTermination(executor);
    }
}
